<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { getProductDetailAPI, getUserGoodsAPI } from '@/api/Goods.js';
import { createExchangeAPI ,getAddressAPI } from '@/api/Trade.js';
import { useUserStore } from "@/stores/user";
import { ElMessage } from 'element-plus';

// 获取用户信息
const store = useUserStore();
const userId = store.UserId;

// 商品详情和交换数据
const productDetail = ref(null);
const selectedExchangeProducts = ref([]); // 多个选择的商品
const exchangeQuantities = ref([]); // 每个选择商品对应的数量
const exchangeQuantity = ref(1);
const userQuantity = ref(1);
const showExchangeModal = ref(false);
const userGoods = ref([]);
// 地址相关数据
const addresses = ref([]);
const selectedAddress = ref(null);
const showAddressModal = ref(false); // 控制地址弹窗显示
// 分页相关变量
const currentPage = ref(1); // 当前页码
const totalGoods = ref(0); // 商品总数
const pageSize = ref(5); // 每页展示的商品数量
const isSelectAll = ref(false); // 是否全选

// 从路由中获取商品ID
const route = useRoute();
const productId = route.query.productId;

// 获取商品详情
const fetchProductDetails = async () => {
  const response = await getProductDetailAPI(productId);
  if (response.data.code === 200) {
    productDetail.value = response.data.data;
  }
};

// 获取用户的商品列表（分页查询）
const fetchUserGoods = async (pageNum = 1) => {
  const response = await getUserGoodsAPI({ userId, pageNum, pageSize: pageSize.value });
  if (response.data.code === 200) {
    userGoods.value = response.data.data.rows;
    totalGoods.value = response.data.data.total; // 设置商品总数
  }
};
// 获取用户的收货地址
const fetchAddresses = async () => {
  const response = await getAddressAPI(userId);
  if (response.data.code === 200) {
    addresses.value = response.data.data;
  }
};
// 打开地址选择弹窗
const openAddressModal = () => {
  showAddressModal.value = true;
  fetchAddresses(); // 获取地址列表
};

// 选择地址
const selectAddress = (address) => {
  selectedAddress.value = address;
  showAddressModal.value = false;
};

// 打开弹窗并获取用户商品
const openExchangeModal = () => {
  showExchangeModal.value = true;
  fetchUserGoods(currentPage.value); // 获取当前页的商品
};

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchUserGoods(newPage); // 请求新的分页数据
};

// 选择/取消选择商品
const toggleSelectProduct = (product) => {
  const index = selectedExchangeProducts.value.findIndex(p => p.id === product.id);
  if (index === -1) {
    selectedExchangeProducts.value.push(product);
    exchangeQuantities.value.push(1); // 默认数量为1
  } else {
    selectedExchangeProducts.value.splice(index, 1);
    exchangeQuantities.value.splice(index, 1);
  }
};



// 移除单个选择的商品
const removeSelectedProduct = (productId) => {
  const index = selectedExchangeProducts.value.findIndex(p => p.id === productId);
  if (index !== -1) {
    selectedExchangeProducts.value.splice(index, 1);
    exchangeQuantities.value.splice(index, 1);
  }
};

// 确认选择商品并关闭弹窗
const confirmSelection = () => {
  showExchangeModal.value = false;
  // ElMessage.success('商品选择成功');
};

// 提交交换订单
const submitExchangeOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.error('请选择收货地址');
    return;
  }
  if (selectedExchangeProducts.value.length === 0) {
    ElMessage.error('请选择要交换的商品');
    return;
  }

  const exchangeGoodsList = selectedExchangeProducts.value.map((product, index) => ({
    exchangeGoodsId: product.id, // 商品ID
    exchangeNum: exchangeQuantities.value[index], // 商品数量
  }));

  const exchangeOrderData = {
    buyerId: userId,
    sellerId: productDetail.value.userId,
    // goodsId为string类型，需要转换成number类型
    goodsId: Number(productId),
    goodsNum: userQuantity.value, // 当前商品数量
    exchangeGoodsList: exchangeGoodsList ,// 交换商品集合
    goodsImage: productDetail.value.image,
    goodsName: productDetail.value.name,
    description: productDetail.value.description,
    price: productDetail.value.price* userQuantity.value,
    mailAddressId: selectedAddress.value.id, // 收货地址ID

  };

  const response = await createExchangeAPI(exchangeOrderData);
  if (response.data.code === 200) {
    ElMessage.success('交换订单提交成功');
  } else {
    ElMessage.error(response.data.msg);
  }
};
// 取消选择商品并关闭弹窗
const cancleSelection = () => {
  showExchangeModal.value = false;
  selectedExchangeProducts.value = [];
  exchangeQuantities.value = [];
};

// 组件挂载时获取商品详情
onMounted(() => {
  fetchProductDetails();
});
</script>

<template>
  <div class="container">
    <h2 class="title">您需要的商品</h2>
    <!-- 商品详情展示 -->
    <el-table v-if="productDetail" :data="[productDetail]" style="width: 1000px;">
      <el-table-column label="图片" width="100">
        <template #default="scope">
          <img :src="scope.row.image" alt="商品图片" class="product-image" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="参考价格" />
      <el-table-column prop="weight" label="重量" />
      <el-table-column label="完好率">
        <template #default="scope">
          {{ scope.row.brokenRate * 100 }}%
        </template>
      </el-table-column>
      <el-table-column label="数量" width="200">
        <template #default="scope">
          <el-input-number v-model="userQuantity" :min="1" :max="productDetail.nums" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 选择交换商品按钮 -->
    <el-button type="primary" @click="openExchangeModal">
      选择交换商品
    </el-button>
    <!-- 选择交换商品弹窗 -->
    <el-dialog title="选择您的商品" v-model="showExchangeModal" width="60%">
      <el-table :data="userGoods" style="width: 100%">
        <el-table-column label="选择" width="80">
          <template #default="scope">
            <el-checkbox :checked="selectedExchangeProducts.some(p => p.id === scope.row.id)" @change="toggleSelectProduct(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="图片" width="120">
          <template #default="scope">
            <img :src="scope.row.image" alt="商品图片" class="product-image" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" />
        <el-table-column label="完好率">
          <template #default="scope">
            {{ scope.row.brokenRate * 100 }}%
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template #default="scope">
            {{ scope.row.nums }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="参考价格" />
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <!-- 添加分页组件 -->
        <el-pagination
            background
            layout="prev, pager, next"
            :total="totalGoods"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="handlePageChange">
        </el-pagination>
      </div>

      <div style="margin-top: 20px;">
           <span slot="footer" class="dialog-footer">
        <el-button @click="cancleSelection"  >取消</el-button>
        <el-button type="primary" @click="confirmSelection">确认选择</el-button>
      </span>
      </div>

    </el-dialog>

    <!-- 用户选择的交换商品详情展示 -->
    <div v-if="selectedExchangeProducts.length > 0" style="margin-top: 20px;">
      <h2>您交换的商品：</h2>
      <el-table :data="selectedExchangeProducts" style="width: 100%">
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <img :src="scope.row.image" alt="交换商品图片" class="product-image" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="price" label="参考价格" />
        <el-table-column prop="weight" label="重量" />
        <el-table-column label="数量" width="200">
          <template #default="scope">
            <el-input-number v-model="exchangeQuantities[selectedExchangeProducts.indexOf(scope.row)]" :min="1" :max="scope.row.nums" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button @click="removeSelectedProduct(scope.row.id)" type="danger" size="mini">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <!-- 选择收货地址按钮 -->
    <el-button type="primary" @click="openAddressModal">
      选择收货地址
    </el-button>

    <!-- 选择的收货地址展示 -->
    <div v-if="selectedAddress" style="margin-top: 20px;">
      <h3>选择的收货地址：</h3>
      <p>{{ selectedAddress.addressee }} - {{ selectedAddress.addresseePhone }}</p>
      <p>{{ selectedAddress.address }}</p>
    </div>

    <!-- 地址选择弹窗 -->
    <el-dialog title="选择收货地址" v-model="showAddressModal" width="40%">
      <el-table :data="addresses" style="width: 100%">
        <el-table-column prop="addressee" label="收件人" />
        <el-table-column prop="addresseePhone" label="联系电话" />
        <el-table-column prop="address" label="地址" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button @click="selectAddress(scope.row)" type="primary" size="mini">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-button type="primary" @click="submitExchangeOrder" class="submit-button">
     确认交换
    </el-button>
  </div>
</template>

<style scoped>
.container {
  padding: 20px;
  margin-top: -25%;
  position: absolute;
  margin-left: -40%;
}
.title {
  font-size: 24px;
  margin-bottom: 20px;
}
.product-image {
  width: 50px;
  height: auto;
}
.dialog-footer {
margin-left: 40%;

}
.submit-button {
  margin-top: 20px;
  margin-left: 90%;
}
.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 20px;       /* 可选：添加顶部间距 */
}
</style>
